// + 该仓库用于存储画布的状态
import type { IJsonSchema } from "@/types/common";
import {
  addOptionStatusItem,
  deleteOptionStatusItem,
  setTextStatus,
  setStatusIndex,
  setPicSelectOptionItem,
  changeEditorVisible,
  setRateIsUse,
} from "./commonActions";
import { initialEditorComs } from "./utils";
import type { ISurveyDB, ISurveyDBReturn } from "@/types";
import useDBOperation from "@/db/operation";

// * 初始化问卷
const initialComs = initialEditorComs();

export const useEditorStore = defineStore("editor", () => {
  // + 当前选中的组件id(默认不选中，所以为-1)
  const currentComId = ref<string>("");

  // + 问卷中组件的列表
  const coms = ref<IJsonSchema[]>([...initialComs]);

  // * 获取当前选中的组件的jsonSchema
  const getCurrentComJsonSchema = computed<IJsonSchema | undefined>(() =>
    coms.value.find((com) => com.id === currentComId.value),
  );

  // * 添加组件
  const insertCom = (com: IJsonSchema, index: number) => {
    coms.value.splice(index, 0, com);
  };

  // * 删除组件
  const deleteComByComId = (id: string) => {
    coms.value = coms.value.filter((com) => com.id !== id);
  };

  // * 设置当前选中的组件id
  const setCurrentComId = (id: string) => {
    currentComId.value = id;
  };

  // * 重置画布
  const resetComs = () => {
    currentComId.value = "";
    coms.value = initialComs;
  };

  // * 保存问卷
  const saveComs = (data: ISurveyDB) => {
    console.log(coms.value, data);
    return useDBOperation.saveSurvey(data);
  };

  // * 设置问卷
  const setComs = (data: IJsonSchema[]) => {
    coms.value = data;
    currentComId.value = "";
  };

  // * 更新问卷
  const updateComs = (data: Partial<ISurveyDBReturn>) => {
    console.log(coms.value, data);
    return useDBOperation.updateSurvey(data.id!, data);
  };

  // * 根据id获取问卷
  const getSurveyById = (id: number) => {
    return useDBOperation.getSurveyById(id);
  };

  // * 删除问卷
  const deleteSurveyById = (id: number) => {
    return useDBOperation.deleteSurvey(id);
  };

  return {
    insertCom,
    deleteComByComId,
    setCurrentComId,
    currentComId,
    getCurrentComJsonSchema,
    coms,
    resetComs,
    saveComs,
    setComs,
    updateComs,
    getSurveyById,
    deleteSurveyById,
    // - 公用方法
    addOptionStatusItem,
    deleteOptionStatusItem,
    setTextStatus,
    setStatusIndex,
    setPicSelectOptionItem,
    changeEditorVisible,
    setRateIsUse,
  };
});
